package com.universe.demo.springboot.filedemo;

import com.alibaba.excel.EasyExcel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/upload")
@Validated
@Slf4j
public class FileUploadController {

    @SneakyThrows
    @PostMapping
    public Object handleFileUpload(MultipartFile file) {

        int rowCount = getRowcount(file);
        //打印行数
        log.info("rowCount: {}", rowCount);

         rowCount = getRowcount(file);
        //打印行数
        log.info("rowCount: {}", rowCount);

        List<UserData> userDataList = new ArrayList<>();

        // 确保文件不为空
        if (file.isEmpty()) {
            throw new RuntimeException("Failed to upload because the file is empty.");
        }

        try {
            // 使用 EasyExcel 解析文件
            EasyExcel.read(file.getInputStream(), UserData.class, new UserDataListener(userDataList)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException("Failed to parse Excel file", e);
        }

        return userDataList;
    }

    // 根据单元格类型返回值
    private String getCellValue(Cell cell) {
        switch (cell.getCellTypeEnum()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    public static int getRowcount(MultipartFile file) {
        try {
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            return sheet.getPhysicalNumberOfRows();
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }


    @PostMapping("/valid")
    public String upload(@ValidFile(allowedExtensions = {"jpg", "png", "pdf","xls","xlsx"}, maxSize = 90 * 1024 * 1024) MultipartFile file) {
        long begin = System.currentTimeMillis();
        log.info("rowcount:{}  耗时：{} ms", getRowcount(file),System.currentTimeMillis() - begin);
        // 业务逻辑处理
        return "File uploaded successfully: " + file.getOriginalFilename();
    }
}
